<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户" prop="custId">
        <!-- <el-input
          v-model="queryParams.custId"
          placeholder="请输入客户ID"
          clearable
          @keyup.enter="handleQuery"
        /> -->
        <el-select v-model="queryParams.custId" placeholder="请选择客户" clearable filterable>
          <el-option
            v-for="dict in custList"
            :key="dict.id"
            :label="dict.custName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable filterable>
          <el-option
            v-for="dict in prdorder_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="合同" align="center" prop="contract.contName" />
      <el-table-column label="客户" align="center" prop="cust.custName" />
      <el-table-column label="订单总额" align="center" prop="totalAmount" />
      <el-table-column label="已结款" align="center" prop="paidAmount" />
      <el-table-column label="欠额" align="center" prop="dueAmount" />
      <el-table-column label="订单状态" align="center" prop="orderStatus" >
        <template #default="scope">
          <dict-tag :options="prdorder_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:order:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:order:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合同" prop="contractId" v-if="form.id">
          <!-- <el-input v-model="form.contractId" placeholder="请输入合同ID" /> -->
          <el-select v-model="form.contractId" placeholder="请选择合同" clearable filterable disabled @change="changeCustId(form.contractId)">
            <el-option
              v-for="dict in contractList"
              :key="dict.id"
              :label="dict.contName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同" prop="contractId" v-if="!form.id">
          <!-- <el-input v-model="form.contractId" placeholder="请输入合同ID" /> -->
          <el-select v-model="form.contractId" placeholder="请选择合同" clearable filterable @change="changeCustId(form.contractId)">
            <el-option
              v-for="dict in noOrderContractList"
              :key="dict.id"
              :label="dict.contName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="客户ID" prop="custId" v-if="false">
          <el-input v-model="form.custId" placeholder="请输入客户ID" />
        </el-form-item> -->
        <el-form-item label="客户" prop="custId" v-if="!form.id">
          <el-select v-model="form.custId" placeholder="请选择客户" clearable filterable disabled="disabled">
            <el-option
              v-for="dict in addcustList"
              :key="dict.id"
              :label="dict.custName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户" prop="custId" v-if="form.id">
          <el-select v-model="form.custId" placeholder="请选择客户" clearable filterable disabled="disabled">
            <el-option
              v-for="dict in custList"
              :key="dict.id"
              :label="dict.custName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="订单总额" prop="totalAmount">
          <el-input type="number" v-model="form.totalAmount" placeholder="请输入订单总额" />
        </el-form-item>
        <el-form-item label="已结款" prop="paidAmount">
          <el-input type="number" v-model="form.paidAmount" placeholder="请输入已结款" />
        </el-form-item>
        <el-form-item label="欠额" prop="dueAmount">
          <el-input type="number" v-model="form.dueAmount" placeholder="请输入欠额" disabled="disabled"/>
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态" clearable filterable disabled="disabled">
            <el-option
              v-for="dict in prdorder_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-divider content-position="center">订单详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTbOrderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteTbOrderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="tbOrderDetailList"  :row-class-name="rowTbOrderDetailIndex" @selection-change="handleTbOrderDetailSelectionChange" ref="tbOrderDetail" width="100%">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="设备" prop="equipmentId" width="150">
            <template #default="scope">
              <!-- <el-input v-model="scope.row.equipmentId" placeholder="请输入设备ID" /> -->
              <el-select v-model="scope.row.equipmentId" placeholder="请选择设备" clearable filterable @change="changeEquipmentId(scope.row.equipmentId,scope.row.index)">
                <el-option
                  v-for="dict in equipmentList"
                  :key="dict.id"
                  :label="dict.equipmentName"
                  :value="dict.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="设备数量" prop="quantity" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入设备数量" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/manage/order";
import { listContract,listNoOrderContract } from "@/api/manage/contract";
import { listCust } from "@/api/manage/cust";
import { loadAllParams } from "@/api/page";
import { ref } from "vue";
import { listEquipment } from "@/api/manage/equipment";


const { proxy } = getCurrentInstance();
const { prdorder_status } = proxy.useDict('prdorder_status');

const orderList = ref([]);
const tbOrderDetailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTbOrderDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    custId: null,
    orderStatus: null,
  },
  rules: {
    contractId: [
      { required: true, message: "合同ID不能为空", trigger: "blur" }
    ],
    custId: [
      { required: true, message: "客户ID不能为空", trigger: "blur" }
    ],
    totalAmount: [
      { required: true, message: "订单总额不能为空", trigger: "blur" },
      //最小值为0
      { validator: (rule, value, callback) => {
          if (value < 0) {
            callback(new Error("订单总额必须大于等于0"));
          } else {
            callback();
          }
        }, trigger: "blur" }
    ],
    paidAmount: [
      { required: true, message: "已结款不能为空", trigger: "blur" },
      { validator: (rule, value, callback) => {
        //将value转换为数字
        value = Number(value);
          if (value < 0) {
            callback(new Error("已结款必须大于等于0"));
          } else if (value > data.form.totalAmount) {
            console.log(value);
            callback(new Error(value+"已结款必须小于等于" + data.form.totalAmount));
          } else {
            callback();
          }
        }, trigger: ["blur","input"] }
    ],
    dueAmount: [
      { required: true, message: "欠额不能为空", trigger: "blur" },
    ],
    orderStatus: [
      { required: true, message: "订单状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);



watch(
  () => [form.value.totalAmount, data.form.paidAmount],
  ([totalAmount, paidAmount]) => {
    if (totalAmount !== null && paidAmount !== null) {
      form.value.dueAmount = totalAmount - paidAmount;
    }
    
    if(totalAmount > paidAmount && paidAmount > 0) {
      form.value.orderStatus = '2';
    }
    else if(totalAmount == paidAmount && totalAmount > 0 ) {
      form.value.orderStatus = '3';
    }else if (paidAmount == 0 ) {
      form.value.orderStatus = '1';
    } else {
      form.value.orderStatus = null;
    }
  }
);


/** 查询订单管理列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    contractId: null,
    custId: null,
    totalAmount: 0, // 设置默认值为0
    paidAmount: 0,  // 设置默认值为0
    dueAmount: 0,   // 设置默认值为0
    orderStatus: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  tbOrderDetailList.value = [];
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    tbOrderDetailList.value = response.data.tbOrderDetailList;
    open.value = true;
    title.value = "修改订单管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      form.value.tbOrderDetailList = tbOrderDetailList.value;
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 订单详情序号 */
function rowTbOrderDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 订单详情添加按钮操作 */
function handleAddTbOrderDetail() {
  let obj = {};
  obj.equipmentId = "";
  obj.quantity = "";
  obj.remark = "";
  tbOrderDetailList.value.push(obj);
}

/** 订单详情删除按钮操作 */
function handleDeleteTbOrderDetail() {
  if (checkedTbOrderDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的订单详情数据");
  } else {
    const tbOrderDetails = tbOrderDetailList.value;
    const checkedTbOrderDetails = checkedTbOrderDetail.value;
    tbOrderDetailList.value = tbOrderDetails.filter(function(item) {
      return checkedTbOrderDetails.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleTbOrderDetailSelectionChange(selection) {
  checkedTbOrderDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

/** 查询所有合同 */
const contractList = ref([]);
function getContractList() {
  listContract(loadAllParams).then(response => {
    contractList.value = response.rows;
  });
}

/** 查询所有客户 */
const custList = ref([]);
function getCustList() {
  listCust(loadAllParams).then(response => {
    custList.value = response.rows;
  });
}

const addcustList = ref([]);
function changeCustId(contId){
   // 假设 contractList 中的每个合同都有一个关联的客户列表
   const selectedContract = contractList.value.find(contract => contract.id === contId);
  if (selectedContract && selectedContract.custId) {
    // 根据合同的 custIds 过滤客户列表
    addcustList.value = custList.value.filter(cust => cust.id === selectedContract.custId);
    form.value.custId=addcustList.value[0].id;
    form.value.custName=addcustList.value[0].custName;
  } else {
    // 如果没有关联的客户，清空客户列表
    custList.value = [];
  }
}
/** 查询所有设备 */
const equipmentList = ref([]);
function getEquipmentList() {
  listEquipment(loadAllParams).then(response => {
    equipmentList.value = response.rows;
  });
}

/** 查询未创建订单的所有合同 */
const noOrderContractList = ref([]);
function getNoOrderContractList() {
  listNoOrderContract().then(response => {
    noOrderContractList.value = response.rows;
  });
}

getNoOrderContractList();
getEquipmentList();
getCustList();
getContractList();
getList();
</script>
